<template>
	<view class="container">
		<map
		:style="{width: system.windowWidth+'px',height: system.windowHeight -system.statusBarHeight- 70 +'px'}" 
		:latitude="latitude" 
		:longitude="longitude" 
		:markers="markers">
		</map>
		<view class="content" @click.stop="toSearch">
			<SearchBar :focus="false" @search="onSearch"></SearchBar>			
		</view>
	</view>
</template>

<script>
import amap from "../../js_sdk/js-amap/amap-wx.js";
import SearchBar from '../index/components/search.vue';
import {mapActions} from 'vuex'
export default{
	data(){
		return{
			latitude:'',//精度
			longitude:'',//维度
			markers:[],//标记点
			id:0, // 使用 marker点击事件 需要填写id
			title: 'map',
			mapInfo:{},//高德地图返回的信息
			showMap:false,//选择地址返回信息后显示地图
			amapPlugin:{},//引用高德地图插件
			system:{},//系统信息
			keyword:'',//搜索关键字
		}
	},
	components:{
		SearchBar
	},
	onLoad() {
		this.getSystemInfo();
		
		// 先尝试从缓存获取位置
		const cachedLocation = uni.getStorageSync('location');
		if (cachedLocation) {
			try {
				const location = JSON.parse(cachedLocation);
				if (location.latitude && location.longitude) {
					this.latitude = location.latitude;
					this.longitude = location.longitude;
					this.showMyLocation({
						latitude: location.latitude,
						longitude: location.longitude,
						id: 'myLocation'
					});
				}
			} catch (e) {
				console.error('解析缓存位置失败', e);
			}
		}
		
		// #ifdef APP-PLUS
		this.init();
		// #endif
		
		// #ifdef H5 || MP-WEIXIN
		// 小程序和H5直接获取定位
		this.getLocation();
		// #endif
	},
	methods:{
		...mapActions(['setLocation']),
		toSearch(){
			uni.navigateTo({
				url:'./search',
			})
		},
		onSearch(e){
			console.log(e);
		},
		// 获取设备宽高
		getSystemInfo(){
			uni.getSystemInfo({
				success: (res) => {
					console.log("设备",res);
					this.system = res;
				},
				fail: (err) => {
					uni.showToast({
						title:JSON.stringify(res),
						icon:'none'
					});
				}
			})
		},
		chooseLocation(){
			this.showMap = true;
			uni.chooseLocation({
				success: (res)=> {
					console.log('位置名称：' + res.name);
					console.log('详细地址：' + res.address);
					console.log('纬度：' + res.latitude);
					console.log('经度：' + res.longitude);
					this.latitude = res.latitude;
					this.longitude = res.longitude;
					this.showMyLocation(res);
				}
			})
		},
		openLocation(){
			uni.openLocation({
				latitude: this.latitude,
				longitude: this.longitude,
				name:this.mapInfo.name,
				address:this.mapInfo.desc,
				success: (response)=> {
					console.log('response',response);
				}
			})
		},
		getLocation(){
			uni.showLoading({
				title:'定位中...'
			})
			uni.getLocation({
				type: 'gcj02', // map组件支持的类型
				altitude: true, // 传入 true 会返回高度信息
				geocode: true, // 设置该参数为 true 会自动解析地址信息
				success: (res) => {
					uni.hideLoading();
					// 修复bug：正确赋值经纬度
					this.latitude = res.latitude;
					this.longitude = res.longitude;
					
					console.log('当前位置的经度：' + res.longitude);
					console.log('当前位置的纬度：' + res.latitude);
					
					// 存储位置信息到Vuex
					this.setLocation({
						latitude: res.latitude,
						longitude: res.longitude
					});
					
					// 显示我的位置标记
					this.showMyLocation({
						latitude: res.latitude,
						longitude: res.longitude,
						id: 'myLocation'
					});
					
					uni.showToast({
						icon: 'success',
						title: '定位成功'
					});
				},
				fail: (err) => {
					uni.hideLoading();
					console.error("定位失败", err);
					
					// 根据错误类型给出提示
					let errorMsg = '定位失败';
					if (err.errMsg) {
						if (err.errMsg.includes('auth deny') || err.errMsg.includes('permission')) {
							errorMsg = '定位权限被拒绝，请在设置中开启';
						} else if (err.errMsg.includes('timeout')) {
							errorMsg = '定位超时，请重试';
						}
					}
					
					uni.showModal({
						title: '定位失败',
						content: errorMsg + '，是否手动选择位置？',
						success: (modalRes) => {
							if (modalRes.confirm) {
								this.chooseLocation();
							} else {
								// 使用默认位置（北京）
								this.latitude = 39.9042;
								this.longitude = 116.4074;
								this.setLocation({
									latitude: this.latitude,
									longitude: this.longitude
								});
							}
						}
					});
				},
				complete: () => {
					uni.hideLoading();
				}
			});
		},
		closeMapMarker(){},
		mapUpdated(){},
		markertap(){},
		// 存储位置
		toSetLocation(res){
			this.setLocation({
				latitude:res.latitude,
				longitude:res.longitude
			});
		},
		// 显示我的位置
		showMyLocation(markers){
			// 先清除旧的位置标记
			this.markers = this.markers.filter(m => m.id !== 'myLocation');
			
			// 添加新的位置标记
			this.markers.push({
				id: markers.id || 'myLocation',
				latitude: markers.latitude,
				longitude: markers.longitude,
				iconPath: '../../static/image/loc/myloc.png',
				width: 30,
				height: 30,
				title: '我的位置',
				callout: {
					content: '我的位置',
					color: '#333',
					fontSize: 12,
					borderRadius: 4,
					bgColor: '#fff',
					padding: 5,
					display: 'BYCLICK'
				}
			});
			
			// 强制更新视图
			this.$forceUpdate();
		},
		init(){
			this.amapPlugin = new amap.AMapWX({
				key:"20549ba8e49a4d6ab1898549debf308e"  //该key 是在高德中申请的微信小程序key
			});
			this.getRegeo();
			this.getPoiAround();
			this.getWeather();
		},
		// 获取地址描述数据
		getRegeo(){
			this.amapPlugin.getRegeo({
				type: 'gcj02', //map 组件使用的经纬度是国测局坐标， type 为 gcj02
				success: (res)=> {
					console.log("高德地图",res);
					const latitude = res[0].latitude;
					const longitude = res[0].longitude;
					this.longitude = longitude;
					this.latitude = latitude;
					this.mapInfo = res[0];
					let markers = res[0];
					this.showMyLocation(markers);
					// this.openLocation();
					// this.getPoiAround();
				},
				fail: (res) => {
					// this.chooseLocation();
					// this.getLocation();
					uni.showToast({
						title:JSON.stringify(res),
						icon:'none'
					});
				}
			});
		},
		// 获取周边服务
		getPoiAround(){
			this.amapPlugin.getPoiAround({
			  success: (data)=>{
				//成功回调
				console.log("附近",data);
				let markers = data.markers;
				markers.map(item=>{
					item.width = '10px';
					item.height = '20px';
					item.iconPath = '../../static/image/map/shop.png';
					item.callout = {
						content:item.name,
						color:'#333',
						fontSize:'14',
						borderRadius:'4',
						bgColor:'#f5f5f5',
						padding:'10',
						display:'BYCLICK',
						// display:'ALWAYS',
						textAlign:'center',
					}
				})
				this.markers = markers;
				this.showMap = true;
			  },
			  fail: (info)=>{
				//失败回调
				console.log("info",info)
			  }
			})
		},
		// 查询指定城市的实时天气和预报天气
		getWeather(){
			this.amapPlugin.getWeather({
			  success: (data)=>{
				//成功回调
				console.log('天气',data);
			  },
			  fail: (info)=>{
				//失败回调
				uni.showToast({
					title:JSON.stringify(info),
					icon:'none'
				});
			  }
			})
		},
		
	}
}
</script>

<style>
.container{
	background-color: transparent;
}
.content{
	width: 100%;
	height: 70px;
	background-color: transparent;
}
</style>
